/// 消息气泡组件
/// 显示聊天消息
library;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:chat_project/models/message_model.dart';
import 'package:chat_project/config/theme_config.dart';

class MessageBubble extends StatelessWidget {
  final Message message;
  final bool isMe;
  final bool showAvatar;
  
  const MessageBubble({
    super.key,
    required this.message,
    required this.isMe,
    this.showAvatar = false,
  });
  
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          // 发送者头像（左侧）
          if (!isMe && showAvatar)
            _buildAvatar(),
          
          // 消息气泡
          Flexible(
            child: Container(
              margin: EdgeInsets.only(
                left: !isMe && showAvatar ? 8 : 0,
                right: isMe && showAvatar ? 8 : 0,
              ),
              padding: const EdgeInsets.symmetric(
                horizontal: ThemeConfig.paddingRegular,
                vertical: ThemeConfig.paddingSmall,
              ),
              decoration: BoxDecoration(
                color: isMe 
                    ? ThemeConfig.outgoingMessageColor 
                    : ThemeConfig.incomingMessageColor,
                borderRadius: BorderRadius.only(
                  topLeft: const Radius.circular(ThemeConfig.borderRadiusRegular),
                  topRight: const Radius.circular(ThemeConfig.borderRadiusRegular),
                  bottomLeft: isMe 
                      ? const Radius.circular(ThemeConfig.borderRadiusRegular) 
                      : const Radius.circular(ThemeConfig.borderRadiusSmall),
                  bottomRight: isMe 
                      ? const Radius.circular(ThemeConfig.borderRadiusSmall) 
                      : const Radius.circular(ThemeConfig.borderRadiusRegular),
                ),
              ),
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              child: Column(
                crossAxisAlignment: isMe 
                    ? CrossAxisAlignment.end 
                    : CrossAxisAlignment.start,
                children: [
                  // 消息内容
                  _buildMessageContent(),
                  
                  // 时间和状态
                  const SizedBox(height: 2),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        _formatTime(message.createdAt),
                        style: TextStyle(
                          fontSize: ThemeConfig.fontSizeSmall,
                          color: isMe 
                              ? Colors.white70 
                              : ThemeConfig.textSecondaryColor,
                        ),
                      ),
                      if (isMe) ...[
                        const SizedBox(width: 4),
                        _buildStatusIcon(),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ),
          
          // 发送者头像（右侧）
          if (isMe && showAvatar)
            _buildAvatar(),
        ],
      ),
    );
  }
  
  // 构建头像
  Widget _buildAvatar() {
    return CircleAvatar(
      radius: 16,
      backgroundColor: ThemeConfig.primaryColor.withOpacity(0.1),
      foregroundImage: NetworkImage(
        message.sender.avatar.startsWith('http')
            ? message.sender.avatar
            : 'http://10.0.2.2:5000${message.sender.avatar}',
      ),
      onForegroundImageError: (_, __) {},
      child: Text(
        message.sender.username.substring(0, 1).toUpperCase(),
        style: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: ThemeConfig.primaryColor,
        ),
      ),
    );
  }
  
  // 构建消息内容
  Widget _buildMessageContent() {
    switch (message.type) {
      case MessageType.image:
        return _buildImageMessage();
      case MessageType.file:
        return _buildFileMessage();
      case MessageType.audio:
        return _buildAudioMessage();
      case MessageType.text:
      default:
        return _buildTextMessage();
    }
  }
  
  // 构建文本消息
  Widget _buildTextMessage() {
    return Text(
      message.content,
      style: TextStyle(
        fontSize: ThemeConfig.fontSizeRegular,
        color: isMe 
            ? Colors.white 
            : ThemeConfig.textPrimaryColor,
      ),
    );
  }
  
  // 构建图片消息
  Widget _buildImageMessage() {
    final url = message.content;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusSmall),
          child: Image.network(
            url,
            width: 200,
            height: 150,
            fit: BoxFit.cover,
            loadingBuilder: (context, child, loadingProgress) {
              if (loadingProgress == null) return child;
              return Container(
                width: 200,
                height: 150,
                alignment: Alignment.center,
                child: CircularProgressIndicator(
                  value: loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded / 
                          loadingProgress.expectedTotalBytes!
                      : null,
                  color: ThemeConfig.primaryColor,
                ),
              );
            },
            errorBuilder: (context, error, stackTrace) {
              return Container(
                width: 200,
                height: 150,
                alignment: Alignment.center,
                color: Colors.grey[300],
                child: const Icon(
                  Icons.error,
                  color: Colors.red,
                ),
              );
            },
          ),
        ),
        const SizedBox(height: 4),
        Text(
          message.fileInfo?['fileName'] ?? '图片',
          style: TextStyle(
            fontSize: ThemeConfig.fontSizeSmall,
            color: isMe 
                ? Colors.white 
                : ThemeConfig.textPrimaryColor,
          ),
        ),
      ],
    );
  }
  
  // 构建文件消息
  Widget _buildFileMessage() {
    final fileName = message.fileInfo?['fileName'] ?? '文件';
    final fileSize = message.fileInfo?['fileSize'] ?? 0;
    
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: ThemeConfig.paddingSmall,
        vertical: ThemeConfig.paddingSmall,
      ),
      decoration: BoxDecoration(
        color: isMe 
            ? ThemeConfig.primaryColor.withOpacity(0.5) 
            : Colors.grey[200],
        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusSmall),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.insert_drive_file,
            color: isMe 
                ? Colors.white 
                : ThemeConfig.primaryColor,
            size: 24,
          ),
          const SizedBox(width: 8),
          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  fileName,
                  style: TextStyle(
                    fontSize: ThemeConfig.fontSizeRegular,
                    color: isMe 
                        ? Colors.white 
                        : ThemeConfig.textPrimaryColor,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                Text(
                  _formatFileSize(fileSize),
                  style: TextStyle(
                    fontSize: ThemeConfig.fontSizeSmall,
                    color: isMe 
                        ? Colors.white70 
                        : ThemeConfig.textSecondaryColor,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建音频消息
  Widget _buildAudioMessage() {
    final duration = message.fileInfo?['duration'] ?? 0;
    
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: ThemeConfig.paddingSmall,
        vertical: ThemeConfig.paddingSmall,
      ),
      decoration: BoxDecoration(
        color: isMe 
            ? ThemeConfig.primaryColor.withOpacity(0.5) 
            : Colors.grey[200],
        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusSmall),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.mic,
            color: isMe 
                ? Colors.white 
                : ThemeConfig.primaryColor,
            size: 24,
          ),
          const SizedBox(width: 8),
          Flexible(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Flexible(
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusSmall),
                    child: Container(
                      height: 20,
                      color: isMe 
                          ? Colors.white.withOpacity(0.3) 
                          : ThemeConfig.primaryColor.withOpacity(0.3),
                      child: CustomPaint(
                        painter: WaveformPainter(
                          color: isMe 
                              ? Colors.white 
                              : ThemeConfig.primaryColor,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  _formatDuration(duration),
                  style: TextStyle(
                    fontSize: ThemeConfig.fontSizeSmall,
                    color: isMe 
                        ? Colors.white 
                        : ThemeConfig.textPrimaryColor,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    
    if (dateTime.year == now.year && 
        dateTime.month == now.month && 
        dateTime.day == now.day) {
      // 今天
      return DateFormat('HH:mm').format(dateTime);
    } else if (dateTime.year == now.year && 
               dateTime.month == now.month && 
               dateTime.day == now.day - 1) {
      // 昨天
      return '昨天 ${DateFormat('HH:mm').format(dateTime)}';
    } else if (dateTime.year == now.year) {
      // 今年
      return DateFormat('MM-dd HH:mm').format(dateTime);
    } else {
      // 以前
      return DateFormat('yyyy-MM-dd HH:mm').format(dateTime);
    }
  }
  
  // 格式化文件大小
  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      final kb = (bytes / 1024).toStringAsFixed(1);
      return '$kb KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      final mb = (bytes / (1024 * 1024)).toStringAsFixed(1);
      return '$mb MB';
    } else {
      final gb = (bytes / (1024 * 1024 * 1024)).toStringAsFixed(1);
      return '$gb GB';
    }
  }
  
  // 格式化音频时长
  String _formatDuration(int seconds) {
    final min = seconds ~/ 60;
    final sec = seconds % 60;
    return '${min.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';
  }
  
  // 构建消息状态图标
  Widget _buildStatusIcon() {
    switch (message.status) {
      case MessageStatus.read:
        return Icon(
          Icons.done_all,
          size: 16,
          color: Colors.white.withOpacity(0.8),
        );
      case MessageStatus.delivered:
        return Icon(
          Icons.done_all,
          size: 16,
          color: Colors.white.withOpacity(0.5),
        );
      case MessageStatus.sent:
      default:
        return Icon(
          Icons.done,
          size: 16,
          color: Colors.white.withOpacity(0.5),
        );
    }
  }
}

// 音频波形绘制器
class WaveformPainter extends CustomPainter {
  final Color color;
  
  WaveformPainter({required this.color});
  
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 2
      ..strokeCap = StrokeCap.round;
    
    final width = size.width;
    final height = size.height;
    const barWidth = 3.0;
    const space = 2.0;
    final bars = (width / (barWidth + space)).floor();
    
    for (int i = 0; i < bars; i++) {
      final x = i * (barWidth + space);
      final barHeight = _getRandomHeight(height, i);
      
      canvas.drawLine(
        Offset(x, (height - barHeight) / 2),
        Offset(x, (height + barHeight) / 2),
        paint,
      );
    }
  }
  
  // 生成随机波形高度
  double _getRandomHeight(double maxHeight, int index) {
    const List<double> pattern = [0.5, 0.7, 0.9, 0.8, 0.6, 0.4, 0.6, 0.8, 0.9, 0.7, 0.5];
    return pattern[index % pattern.length] * maxHeight;
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
} 